#!/usr/bin/env
__author__ = 'Gordon Sun'
import sys
import argparse

'''
This file contains functions for display and writing of messages to terminal and to the output file; and for obtaining
the arguments input by the user.
'''
# function for verifying user input
# I: <string> Query message, <string> error message, what <type> of input is expected
# O: User input
def try_except(query, error_msg, input_type):
    while True:
        try:
            i = raw_input(query)
            if input_type == int:
                i = int(i)
            elif input_type == float:
                i = float(i)
            if isinstance(i, input_type):
                break
            else:
                ValueError
        except ValueError:
            print error_msg
            continue
    return i


# function takes in the arguments for the script as well as provides a help interface for the program.
# Program accepts at minimum 2 arguments, but 4 arguments is optimal. Arguments accepted are:
# -if input file
# -c organism codong frequency usage
# -m mode (i) for infusion, (g) for gibson, and (p) for protein optimization
# -o output filename.
# If no output filename arg is given, output file will be input_filename+.output suffix.
# If no organism codon frequency is given, default is E. coli k12.
def get_args(args):
    parser = argparse.ArgumentParser(description='Run Program')
    parser.add_argument("-if", dest='input_file', help='Input filename', required=True)
    parser.add_argument("-c", dest='organism_codon_filename', help='Organism codon freq filename', default="ecoliK12")
    parser.add_argument("-m", dest='mode', help='Procedure:\n (g)ibson,\n (p)rotein optimization', required=True)
    parser.add_argument('-o', dest='output', help='Output filename', default="")
    parser.add_argument('-t', dest='speed', help='How fast you want the program to run, larger number is slower',
                        default=1)

    # If out is empty string, make it the input filename
    options = vars(parser.parse_args())
    if not options['output']:
        options['output'] = options['input_file'] + ".output"
    return options


# function closes the output file and shuts down the program.
# this is the formal fuck it option
def quit_flush(outputfile):
    outputfile.close()
    sys.exit()


# function takes in an output filename and a message to print and write to the output file
# I: message <str> and a filename <str>
# O: prints the <str> to terminal and writes it to the file
def write_n_print(message, outputfilename):
    print message
    outputfilename.write(str(message))
